<template>
  <div>
    <div
      class="flavor"
      :style="{
        backgroundColor: flavorForm.length > 0 ? '#fafafa' : '#fff',
        border: flavorForm.length > 0 ? '1px solid #e8e8e8' : 'none'
      }"
    >
      <header v-if="flavorForm.length > 0">口味名（3个字内）</header>
      <ul class="list">
        <li class="item mt-3" v-for="(flavor, index) in flavorForm" :key="flavor.name">
          <el-row style="width: 100%">
            <el-select v-model="flavor.name" @change="selectChange(index)">
              <el-option :value="item.name" v-for="item in flavorList" :key="item.value" :label="item.name" />
            </el-select>
            <div class="box">
              <el-tag closable type="primary">
                {{ flavor.value }}
              </el-tag>
            </div>
            <el-button type="danger" link class="ml-2 mr-3" @click="deleteFlavor(index)">删除</el-button>
          </el-row>
        </li>
      </ul>
      <el-button type="primary" @click="addFlavor">添加口味</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, defineProps, watch } from "vue"

const props = defineProps<{
  modelValue: any[]
}>()

const emit = defineEmits(["update:modelValue"])

// 口味表单
const flavorForm = ref(props.modelValue)

// 口味列表
const flavorList = [
  {
    name: "甜味",
    value: "全糖"
  },
  {
    name: "辣度",
    value: "微辣"
  },
  {
    name: "温度",
    value: "常温"
  },
  {
    name: "忌口",
    value: "不吃葱花"
  }
]

// 添加口味
const addFlavor = () => {
  //   判断表单中是否还存在空的口味项，如果存在空的口味香，就不再新增
  if (flavorForm.value.some((item) => !item.name)) return
  flavorForm.value.push({
    name: "",
    value: ""
  })
}

// 选项切换
const selectChange = (index: number) => {
  //@ts-ignore
  flavorForm.value[index].value = flavorList.find((item) => item.name === flavorForm.value[index].name).value
  //   将数据提交给父组件
  emit(
    "update:modelValue",
    flavorForm.value.filter((item) => item.name)
  )
}

// 删除对应口味
const deleteFlavor = (index: number) => {
  flavorForm.value.splice(index, 1)
  emit(
    "update:modelValue",
    flavorForm.value.filter((item) => item.name)
  )
}

watch(
  () => props.modelValue,
  () => {
    flavorForm.value = props.modelValue
  }
)
</script>

<style scoped lang="scss">
.flavor {
  // background-color: #fafafa;
  border-radius: 5px;
  min-width: 800px;
  width: 100%;
  padding: 10px;
  //   border: 1px solid #e8e8e8;
  .list {
    list-style: none;
    li {
      width: 100%;
      .el-row {
        display: flex;
        flex-wrap: nowrap;
        .el-select {
          width: 200px;
        }
        .box {
          flex: 1;
          margin-left: 20px;
          background-color: #fff;
          box-shadow: 0 0 0 1px var(--el-border-color) inset;
          border-radius: var(--el-border-radius-base);
          .el-tag {
            margin: 5px;
          }
        }
      }
    }
  }
}
</style>
